package cn.e3mall.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e3mall.common.CookieUtils;
import cn.e3mall.common.E3Result;
import cn.e3mall.common.JsonUtils;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.sso.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;
	@Value("${COOKIE_TOKEN_KEY}")
	private String COOKIE_TOKEN_KEY;
	
	@RequestMapping("/user/check/{param}/{type}")
	@ResponseBody
	public E3Result checkData(@PathVariable String param, @PathVariable Integer type) {
		E3Result e3Result = userService.checkData(param, type);
		return e3Result;
	}
	
	@RequestMapping(value="/user/register", method=RequestMethod.POST)
	@ResponseBody
	public E3Result register(TbUser user) {
		E3Result result = userService.createUser(user);
		return result;
	}
	
	@RequestMapping(value="/user/login", method=RequestMethod.POST)
	@ResponseBody
	public E3Result login(String username, String password,
			HttpServletRequest request, HttpServletResponse response) {
		// 1、接收两个参数。
		// 2、调用Service进行登录。
		E3Result result = userService.login(username, password);
		// 登录失败
		if(result.getStatus() != 200) {
			return result;
		}
		// 3、从返回结果中取token，写入cookie。Cookie要跨域。
		String token = result.getData().toString();
		CookieUtils.setCookie(request, response, COOKIE_TOKEN_KEY, token);
		// 4、响应数据。Json数据。e3Result，其中包含Token。
		return result;
		
	}
	
	@RequestMapping(value="/user/token/{token}",
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	@ResponseBody
	public String getUserByToken(@PathVariable String token, String callback) {
		E3Result result = userService.getUserByToken(token);
		if(StringUtils.isNotBlank(callback)) {
			String strResult = callback + "(" + JsonUtils.objectToJson(result) +");";
			return strResult;
		}
		return JsonUtils.objectToJson(result);
	}
	
	@RequestMapping("/user/quit/{token}")
	@ResponseBody
	public E3Result quitUserByToken(@PathVariable String token) {
		return userService.deleteUserByToken(token);
	}
}
